﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Globalization;

namespace Medianamik.UI.Web.ModalWindows
{
    public partial class AddResourceWindow : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Title = Resources("Medianamik_ResourceManagement", "AddResource");
            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void Add(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var resourceSet = ddlResourceSets.Text;
                var resourceId = txtResourceId.Text;

                var values = new Dictionary<string, string>();
                foreach (RepeaterItem item in rptValues.Items)
                {
                    var localeField = item.FindControl("locale") as HiddenField;
                    var txtValue = item.FindControl("value") as TextBox;
                    if (txtValue != null && localeField != null)
                    {
                        var localeId = localeField.Value;
                        var value = txtValue.Text.Trim();
                        if (value.Length > 0)
                        {
                            values.Add(localeId, value);
                        }
                    }
                }

                var manager = new MedianamikResourceDataManager();
                // ressource neutre à la langue
                manager.AddResource(resourceId, "[" + resourceSet + ", " + resourceId + "]", string.Empty, resourceSet,
                                    false);
                foreach (var resource in values)
                {
                    manager.AddResource(resourceId, resource.Value, resource.Key, resourceSet, false);
                }
                MedianamikResourceConfiguration.ClearResourceCache();

                ScriptManager.RegisterStartupScript(this, typeof (AddResourceWindow),
                                                    "CloseWindow", "closeWindow('ReloadResourceSets');", true);
            }
        }

        protected void BindData()
        {
            var manager = new MedianamikResourceDataManager();
            ddlResourceSets.DataSource = manager.GetAllResourceSets(ResourceListingTypes.AllResources);
            ddlResourceSets.DataTextField = "ResourceSet";
            ddlResourceSets.DataValueField = "ResourceSet";
            ddlResourceSets.DataBind();

            rptValues.DataSource = MedianamikCultures;
            rptValues.DataBind();
        }
    }
}